package com.fangtao.servlet;

import com.alibaba.fastjson.JSONArray;
import com.fangtao.domain.Role;
import com.fangtao.domain.User;
import com.fangtao.service.RoleService;
import com.fangtao.service.UserService;
import com.fangtao.utils.Constants;
import com.fangtao.utils.PageSupport;
import com.mysql.cj.util.StringUtils;
import jdk.nashorn.internal.runtime.Context;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ChangePawServlet
 * @Description TODO
 * @date 2022/9/22 22:37
 * @author: fangtao
 * @Version 1.0
 */
public class ChangePawServlet extends HttpServlet {
    private UserService userService=new UserService();
    private RoleService roleService=new RoleService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println(method);
        if(method != null && method.equals("add")){
            this.add(req, resp);//增加操作
        }else if(method.equals("savepwd")){
         this.changePassword(req,resp);
        }else if(method.equals("pwdmodify")){
          this.updatePwd(req,resp);
        }else if(method.equals("query")){
          this.query(req,resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req, resp);
        }else if(method != null && method.equals("getrolelist")){
            this.getRoleList(req, resp);
        }else if(method != null && method.equals("deluser")){//删除用户
            this.delUser(req, resp);
        }else if(method != null && method.equals("modifyexe")){
            this.modify(req, resp);
        }else if(method != null && method.equals("modify")){
            this.getUserById(req, resp,"usermodify.jsp");
        }



    }

//    带参数id修改页面跳转
    protected void getUserById(HttpServletRequest request, HttpServletResponse response,String url) throws ServletException, IOException {
        String id = request.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            int uid = Integer.parseInt(id);
            User user = userService.getUserById(uid);
            request.setAttribute("user", user);
            request.getRequestDispatcher(url).forward(request, response);
        }
    }

//    修改user数据
    protected void modify(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());


        if(userService.modify(user)){
            try {
                response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                request.getRequestDispatcher("usermodify.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
//    根据id删除用户
    protected  void delUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uid = request.getParameter("uid");
        Integer id=0;

        try {
            id=Integer.parseInt(uid);
        } catch (NumberFormatException e) {
            id=0;

        }
        Map<String,String>resultMap=new  HashMap<String,String>();
        if (id<=0){
            resultMap.put("delResult","false");
        }
        else if (userService.deleteUserById(id)>0){
            resultMap.put("delResult","true");
        }else {
            resultMap.put("delResult","false");
        }
        //把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();

    }
    //提供所有的角色以供选择
    protected void getRoleList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Role> roleList = null;
        roleList = roleService.ListRole();
        //把roleList转换成json对象输出
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    //判断用户账号是否可用
private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userCode = request.getParameter("userCode");

    HashMap<String, String> resultMap = new HashMap<String, String>();
    if(StringUtils.isNullOrEmpty(userCode)){
        //userCode == null || userCode.equals("")
        resultMap.put("userCode", "exist");
    }else{

        User user = userService.selectUserCodeExist(userCode);
        if(null != user){
            resultMap.put("userCode","exist");
        }else{
            resultMap.put("userCode", "notexist");
        }
    }

    //把resultMap转为json字符串以json的形式输出
    //配置上下文的输出类型
    response.setContentType("application/json");
    //从response对象中获取往外输出的writer对象
    PrintWriter outPrintWriter = response.getWriter();
    //把resultMap转为json字符串 输出
    outPrintWriter.write(JSONArray.toJSONString(resultMap));
    outPrintWriter.flush();//刷新
    outPrintWriter.close();//关闭流
}
    //增加用户操作
    protected  void add(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
      //获取前端传来的数据
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());

        if(userService.add(user)){
            try {
                response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                request.getRequestDispatcher("useradd.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
    //用户列表查询页面
    protected  void query(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        String queryUserName = req.getParameter("queryname");
//        String temp = req.getParameter("queryUserRole");
//        String pageIndex = req.getParameter("pageIndex");
//        int queryUserRole=0;
//        if(queryUserName==null){
//            queryUserName="";
//        }
        //查询用户列表

        //从前端获取数据
        String queryUserName = request.getParameter("queryname");
        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表



        //第一次走页面一定是第一页,页面大小固定的
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        /**
         * http://localhost:8090/SMBMS/userlist.do
         * ----queryUserName --NULL
         * http://localhost:8090/SMBMS/userlist.do?queryname=
         * --queryUserName ---""
         */
//        System.out.println("queryUserName servlet--------"+queryUserName);
//        System.out.println("queryUserRole servlet--------"+queryUserRole);
//        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询赋值
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                response.sendRedirect("error.jsp");
            }
        }
        //总数量（表）
        int totalCount	= userService.getCount(queryUserName,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();

        pages.setCurrentPageNo(currentPageNo);

        pages.setPageSize(pageSize);

        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }


        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;

        roleList = roleService.ListRole();
        request.setAttribute("roleList", roleList);
        request.setAttribute("queryUserName", queryUserName);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("userlist.jsp").forward(request, response);
    }
//    判断旧密码情况的方法
protected void updatePwd(HttpServletRequest req, HttpServletResponse resp){
    User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);
    Object o = req.getParameter("oldpassword");
    Map<String,String>resultMap=new HashMap<String, String>();
    if (user==null){
       resultMap.put("result","sessionerror");
    }else if(o==null){
        resultMap.put("result","error");
    }else {
        if (user.getUserPassword().equals((String)o)){
            resultMap.put("result","true");
        }else {
            resultMap.put("result","false");
        }
    }


    try {
        resp.setContentType("application/json");
        PrintWriter writer=resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }


}
//    修改密码的方法提出来，方便代码复用
    protected  void  changePassword(HttpServletRequest req, HttpServletResponse resp){
        User attribute = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int id=(int)attribute.getId().intValue();
        String newpassword=req.getParameter("newpassword");
        if (userService.updatePwd(id,newpassword)&&newpassword!=null){
            req.setAttribute("message","修改成功，请使用新密码重新登录");
            req.getSession().removeAttribute(Constants.USER_SESSION);
            try {
                resp.sendRedirect("/smb/login.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            req.setAttribute("message","修改失败");
            try {
                req.getRequestDispatcher("jsp/pwdmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
